package top.stmo.blog.admin.service;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import top.stmo.blog.admin.pojo.Admin;
import top.stmo.blog.admin.pojo.Permission;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Service
public class AuthService {

    @Autowired
    private AdminService adminService;

    public boolean auth(HttpServletRequest request, Authentication authentication) {
        //权限认证
        //请求路径
        String requestURI = request.getRequestURI();
        //获取当前登录用户信息
        Object principal = authentication.getPrincipal();
        if(principal == null || "anonymousUser".equals(principal)) {
            //未登录
            return false;
        }
        //强转
        UserDetails userDetails = (UserDetails) principal;
        //获取用户名
        String username = userDetails.getUsername();
        //通过用户名在数据库中查询用户信息
        Admin admin = adminService.findAdminByUsername(username);
        //为空说明用户不存在
        if(admin == null) {
            return false;
        }

        //adminId为1是超级管理员，无需做权限判定
        if(admin.getId() == 1) {
            return true;
        }
        //通过用户获取用户ID
        Long adminId = admin.getId();
        //通过用户Id查询其权限信息
        List<Permission> permissions = this.adminService.findPermissionByUsername(adminId);
        //字符串以？分割

        requestURI = StringUtils.split(requestURI,"?")[0];
        for(Permission permission : permissions) {
            if(requestURI.equals(permission.getPath())) {
                return true;
            }
        }
        return false;
    }


}
